import { Body, Controller, Get, Header, Options, Post, Query, Res, StreamableFile } from '@nestjs/common';
import { AppService } from './app.service';
import { FormDataRequest } from 'nestjs-form-data';
import { v4 as uuidv4 } from 'uuid';
import { Readable } from 'stream';
import { InjectRedis } from '@nestjs-modules/ioredis';
import { Redis } from 'ioredis';
const fs = require('fs');
const path = require('path');

@Controller()
export class AppController {
  constructor(
    private readonly appService: AppService,
    @InjectRedis()
    private readonly redis: Redis,
  ) {}

  @Get()
  getHello(): string {
    return this.appService.getHello();
  }
  @Get('savePage')
  async savePage(@Query() query, @Res() res) {
    let html = await this.redis.get(`chrome-page-save-${query.id}`);
    if (html) {
      res.set("Content-disposition", `attachment; filename=${query.pageName}.html`);
      Readable.from([html]).pipe(res);
    } else {
      return '文件不存在';
    }
  }
  @Options('savePageToId')
  @Header('Access-Control-Allow-Origin', '*')
  @Header("Access-Control-Allow-Methods", "GET, POST")
  savePageToIdOption(): string {
    return '';
  }
  @Post('savePageToId')
  @Header('Access-Control-Allow-Origin', '*')
  @Header("Access-Control-Allow-Methods", "GET, POST")
  @FormDataRequest({
    limits: {
      fieldSize: 100000000000
    }
  })
  savePageToId(@Body() body): string {
    let id = uuidv4();
    this.redis.set(`chrome-page-save-${id}`, body.body, 'EX', 1000 * 60 * 5);
    return id;
  }
}
